package cn.fintecher.gis.web;

import cn.fintecher.gis.annotation.CurrentOperator;
import cn.fintecher.gis.model.session.SessionModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import java.util.Objects;

/**
 * Created by ChenChang on 2018/9/4.
 */


public class CurrentOperatorMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private RedisTemplate<String, SessionModel> sessionOperatorRedisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SessionModel.class)
                && parameter.hasParameterAnnotation(CurrentOperator.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String accessToken = webRequest.getHeader("X-OperatorToken");
        SessionModel userModel = sessionOperatorRedisTemplate.opsForValue().get("operator:token:" + accessToken);
        if (Objects.nonNull(userModel)) {
            return userModel;
        }
        throw new MissingServletRequestPartException("currentOperator");
    }

}
